<template>
  <el-container>
    <el-header>
      <Title :title='title1' :SecTitle='title2'></Title>
    </el-header>
    <el-main id="find">
      <span class="mar-right">部门</span>
      <el-input v-model="findData.name" placeholder="请输入企业" maxlength='100'></el-input>
      <span class="mar-right mar-left">状态</span>
      <el-select v-model="findData.useStatus" placeholder="请选择">
        <el-option v-for="item in state_options" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-button class="mar-left" @click="findDepartment" type="primary">查找</el-button>
      <el-button class="mar-left" type="primary" @click="dialogFormVisible1 = true">添加</el-button>
      <el-dialog title="添加" :visible.sync="dialogFormVisible1" style="width:auto; text-align:center;">
        <el-form :model="newform" :rules="rules" ref="newform">
          <el-form-item label="部门名称:" :label-width="formLabelWidth" prop="name">
            <el-input v-model="newform.name" autocomplete="off" class="input_width" placeholder="请输入部门名称"></el-input>
          </el-form-item>
          <el-form-item label="职能描述:" :label-width="formLabelWidth" prop="description">
            <el-input v-model="newform.description" autocomplete="off" class="input_width" placeholder="请输入职能描述"></el-input>
          </el-form-item>
          <el-form-item v-model="newform.useStatus" label="状态:" prop="useStatus" :label-width="formLabelWidth" style="text-align:left;">
            <el-radio v-model="newform.useStatus" label="1">启用</el-radio>
            <el-radio v-model="newform.useStatus" label="0">禁用</el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible1 = resetForm('newform')">取消</el-button>
          <el-button type="primary" @click="dialogFormVisible1 = add('newform')">确定</el-button>
        </div>
      </el-dialog>
    </el-main>
    <el-main id="content">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="name" label="部门名称" width="188.33333333" header-align="center" align="center">
        </el-table-column>
        <el-table-column prop="description" label="职责描述" width="188.33333333" header-align="center" align="center">
        </el-table-column>
        <el-table-column prop="member" label="用户成员" width="188.33333333" header-align="center" align="center">
        </el-table-column>
        <el-table-column prop="created" label="创建时间" width="188.33333333" header-align="center" align="center">
        </el-table-column>
        <el-table-column prop="useStatus" label="状态" width="188.33333333" header-align="center" align="center">
        </el-table-column>
        <el-table-column label="操作" align="center" width="160.33333333">
          <template slot-scope="scope">
            <el-button size="mini" type="success" @click="dialogFormVisible2 = handleEditing(scope.$index, scope.row)">编辑</el-button>
            <el-dialog title="编辑" :visible.sync="dialogFormVisible2">
              <el-form :model="oldForm" :rules="rules" ref="oldForm">
                <el-form-item label="部门名称:" :label-width="formLabelWidth" prop="name">
                  <el-input v-model="oldForm.name" autocomplete="off" class="input_width" placeholder="请输入部门名称"></el-input>
                </el-form-item>
                <el-form-item label="职能描述:" :label-width="formLabelWidth" prop="description">
                  <el-input v-model="oldForm.description" autocomplete="off" class="input_width" placeholder="请输入职能描述"></el-input>
                </el-form-item>
                <el-form-item label="状态:" prop="useStatus" :label-width="formLabelWidth" style="text-align:left;">
                  <el-radio v-model="oldForm.useStatus" label="1">启用</el-radio>
                  <el-radio v-model="oldForm.useStatus" label="0">禁用</el-radio>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible2 = resetForm('oldForm')">取 消</el-button>
                <el-button type="primary" @click="dialogFormVisible2 = submit('oldForm')">确定</el-button>
              </div>
            </el-dialog>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
     <Page
        @pagesizeChange="getPagesize"
        @currentPageChange="getCurrentPage"
        :total="total"
        :pagesize="findData.pageSize"
        :currentPage="findData.page"
      ></Page>
    </el-main>
    <el-main></el-main>
  </el-container>
</template>

<script>
import Title from '@/components/common/title.vue'
import Page from '@/components/paging/paging.vue'
export default {
  data() {
    return {
      total: 0,
      title1: '系统管理',
      title2: '部门管理',
      findData: {
        useStatus: '',
        name: '',
        page: 1,
        pageSize:4
      },
      state_options: [
        {
          value: 0,
          label: '禁用'
        },
        {
          value: 1,
          label: '启用'
        }
      ],
      stateOption: '',
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      newform: {
        name: '',
        description: '',
        useStatus: ''
      },
      oldForm: {
        name: '',
        description: '',
        useStatus: '',
        id: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入职能描述', trigger: 'blur' }
        ],
        useStatus: [
          { required: true, message: '请选择', trigger: 'blur' }
        ]
      },
      formLabelWidth: '120px',
      tableData: []
    }
  },
  components: {
    Title,
    Page
  },
  methods: {
    async deleteDepartment(id) {
      const { data: res } = await this.axios({
        method: "get",
        url: "/department/delete/" + id,
        
      })
      this.getData();
      console.log(res)
    },
    async changeDepartemnt() {
      const { data: res } = await this.axios({
        method: "POST",
        url: "/department/update",
        data: {
          name: this.oldForm.name,
          description: this.oldForm.description,
          useStatus: this.oldForm.useStatus,
          id: this.oldForm.id
        },
       
      })
      this.getData();
      console.log(res)
    },
    async getData() {
      const { data: res } = await this.axios({
        method: "POST",
        url: "/department/list",
        data: {
          useStatus: this.findData.useStatus,
          name: this.findData.name,
          page: this.findData.page,
          pageSize: this.findData.pageSize
        },
       
      })
      if (res.code == 0) {
        this.total = res.count
        this.tableData = res.data;
        this.tableData.forEach(element => {
          element.created = this.timestampToTime(element.created)
          if (element.useStatus == 0) {
            element.useStatus = '禁用'
          } else {
            element.useStatus = '启用'
          }
        });
      }
      console.log(res)
    },
    async addDepartment() {
      const { data: res } = await this.axios({
        method: "POST",
        url: "/department/add",
        data: {
          name: this.newform.name,
          description: this.newform.description,
          useStatus: this.newform.useStatus
        },
     
      })
      this.getData();
    },
    getPagesize(val) {
      this.findData.pageSize = val;
      this.getData();
    },
    //子组件传入CurrentPage
    getCurrentPage(val) {
      this.findData.page = val;
      this.getData();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      return false
    },
    add(formName) {
      let stuta;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          /* 这里发起请求 */
          stuta = false;
          this.addDepartment();
          console.log('通过');
          //清空表单
          this.$refs[formName].resetFields();
        } else {
          stuta = true;
          console.log('失败');
          //清空表单
        }
      });
      return stuta;
    },
    handleEditing(index, item) {
      this.oldForm.id = item.id;
      return true;
    },
    timestampToTime(time) {
      // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var date = new Date(time)
      let y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? ('0' + MM) : MM
      let d = date.getDate()
      d = d < 10 ? ('0' + d) : d
      let h = date.getHours()
      h = h < 10 ? ('0' + h) : h
      let m = date.getMinutes()
      m = m < 10 ? ('0' + m) : m
      let s = date.getSeconds()
      s = s < 10 ? ('0' + s) : s
      return y + '年' + MM + '月' + d + '日'
    },
    submit(formName) {
      let stuta;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          /* 这里发起请求 */
          stuta = false;
          this.changeDepartemnt();
          console.log('通过');
          // console.log('oldForm', this.oldForm.compony, '#####', this.oldForm.state)
          //清空表单
          setTimeout(() => {
            this.$refs[formName].resetFields();
          }, 100);
        } else {
          stuta = true;
          console.log('失败');
          //清空表单
        }
      });
      return stuta;
    },
    handleDelete(index, row) {
      var that = this;
      this.$confirm('此操作将删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {
        await this.deleteDepartment(row.id);//await可以让异步同步执行
        // await this.getData();
        that.tableData.some((item) => {
          if (item.compony == row.compony) {
            that.tableData.splice(index, 1)
            return true
          }
        })
        this.$message({
          type: 'success',
          message: '删除成功!',
          duration: 700
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
          duration: 700
        });
      })
    },
    findDepartment() {
      this.getData();
    }
  },
  created() {
    this.getData();
  }
}

</script>

<style lang="less" scoped>
#find {
  padding: 20px 10px;
  background-color: white;
  margin-top: 30px;
  border-radius: 5px;
  > div {
    width: 200px;
  }
}
.mar-right {
  margin-right: 10px;
}
.mar-left {
  margin-left: 20px;
}
#content {
  padding: 20px 10px;
  background-color: white;
  margin-top: 30px;
  border-radius: 5px;
  height: 489px;
  overflow: hidden;
}
#content:hover {
  overflow: auto;
}
.el-table::before {
  display: none !important;
}
</style>